'''
Created on Jul 3, 2009

@author: bryan
'''

import sys
import os
import csv
import string
import pylab
import numpy as np

def run(filename):
#===============================================================================
#    Read the file supplied
#===============================================================================
    try:
        reader = csv.reader(open(filename, 'rt'),dialect='excel-tab')
        print 'Processing: ', filename
    except:
        print 'Could not open file'
        return
    
    data = np.array([])
    headers = reader.next()
    n_elements = len(headers)
    for row in reader:
        if len(row) == n_elements: 
            # Dont append partial rows
            data = np.append(data,np.asarray(row,'f'))

    data = data.reshape((data.shape[0]/n_elements,n_elements))
    print 'Shape: ', data.shape
    if data.shape[0] is 0:
        print "No data in selected file: ", filename
        main()
        return

#===============================================================================
#     Plot the data
#===============================================================================
    pylab.figure()
    pylab.draw()
    pylab.subplot(311)
    pylab.plot(data[:,2],'b-',
               data[:,3],'g-',
               data[:,4],'r-')
    pylab.ylabel('Translations (mm)')
    pylab.subplot(312)
    pylab.plot(data[:,5],'b-',
               data[:,6],'g-',
               data[:,7],'r-')
    pylab.ylabel('Rotations (deg)')
    pylab.subplot(313)
    pylab.plot(data[:,1])
    pylab.plot(data[:,8],'g-', lw=2)
    pylab.ylabel('Function Value')
    pylab.subplot(311)
    pylab.title(os.path.basename(filename))
    pylab.show()
  
    
def main(input=None):
    """
    Parse command line arguments
    """
    print 'Plotting Results...'
    # TODO: allow the user to specify path to logs
    dir = 'C:/Users/bryan/bryan-code/trunk/Tests/log'
    
#===============================================================================
# Open the file in a python CSV reader
#===============================================================================
    if (len(sys.argv) < 2) or sys.argv[0].endswith('ipython.py'):
        # No file specified, plot last file
        print 'no file specified, using most recent'
        content = {}
        for item in os.listdir(dir):
            content[os.path.join(dir,item)] = os.path.getmtime(os.path.join(dir,item)) 
        f_sorted = sorted(content, key=content.__getitem__, reverse=True)
        if input is None:
            print "Select a log file to be plotted:"
            for i,f in enumerate(range(np.min(10,len(f_sorted)))):
                name = os.path.basename(f_sorted[i])
                print "%i :: %s" % (i,name)
            input = string.atoi((raw_input('\nSelection: ')))
        
        filename = f_sorted[input]
            
    elif os.path.isfile(sys.argv[1]):
        # Given a path to an existing file
        print 'good file given'
        filename = sys.argv[1]
        
    elif os.path.isfile(os.path.join(dir,sys.argv[1])):
        # Given a file, not in the current directory, but in the default directory
        print 'good file given, for default dir'
        filename = os.path.join(dir,sys.argv[1])
    else:
        print sys.argv
        print 'bad file'
        return
    
    run(filename)
    
    

if __name__ == '__main__':
    
    main()